package com.qipay.sp.excutor.qmpay;

import com.qipay.baas.model.Order;
import com.qipay.scalar.type.ApiTypeEnum;
import com.qipay.sp.excutor.AbstractExcutor;
import com.qipay.utils.JsonUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class QmpayWxNativeExcutor extends AbstractExcutor {

    private final static String CONFIG_KEY_NAME="key";
    private final static String CONFIG_MCHID_NAME="mch_id";
    private final static String CONFIG_IP_NAME="ip";
    private final static String SIGN_NAME="sign";
    private final static String API_PARAM_SERVER_CALLBACK_URL="serverCallbackUrl";
    private final static String API_PARAM_TRX_TYPE="trxType";
    private final static String API_PARAM_MERCHANT_NO="merchantNo";
    private final static String API_PARAM_ORDER_NUM="orderNum";
    private final static String API_PARAM_AMOUNT="amount";
    private final static String API_PARAM_GOODS_NAME="goodsName";
    private final static String API_PARAM_ORDER_IP="orderIp";
    private final static String API_PARAM_TIME_OUT="timeOut";
    private final static String API_PARAM_SETTLE_TYPE="settleType";
    private final static String API_URL="http://47.94.167.186:8085/qmpaytrx/trxfront/gateway";

    @Override
    protected ApiTypeEnum getApiTypeEnum() {
        return ApiTypeEnum.WX_NATIVE;
    }

    @Override
    protected Map<String, Object> getApiParams(Order order, Map<String, Object> spconfig, Map<String, Object> extendOrderParams) {
        Map<String, Object> apiParams = new HashMap<>();
        apiParams.put(QmpayWxNativeExcutor.API_PARAM_ORDER_NUM, order.getTradeNo());
        apiParams.put(QmpayWxNativeExcutor.API_PARAM_GOODS_NAME, order.getBody());
        apiParams.put(QmpayWxNativeExcutor.API_PARAM_AMOUNT, new BigDecimal(order.getAmount()).divide(new BigDecimal(100)));
        apiParams.put(QmpayWxNativeExcutor.API_PARAM_TIME_OUT, DateFormatUtils.format(DateUtils.addMinutes(new Date(),30),"yyyyMMddHHmmss"));
        return apiParams;
    }

    @Override
    protected Map<String, Object> run(Map<String, Object> spconfig, Map<String, Object> params) throws Exception {


        Object key = getVal(spconfig, QmpayWxNativeExcutor.CONFIG_KEY_NAME);
        Object orderIp = getVal(spconfig, QmpayWxNativeExcutor.CONFIG_IP_NAME);
        Object trxType = getVal(params, QmpayWxNativeExcutor.API_PARAM_TRX_TYPE);
        Object orderNum = getVal(params, QmpayWxNativeExcutor.API_PARAM_ORDER_NUM);
        Object merchantNo = getVal(spconfig, QmpayWxNativeExcutor.CONFIG_MCHID_NAME);
        Object amount = getVal(params, QmpayWxNativeExcutor.API_PARAM_AMOUNT);
        Object goodsName = getVal(params, QmpayWxNativeExcutor.API_PARAM_GOODS_NAME);
        Object serverCallbackUrl = getVal(params, QmpayWxNativeExcutor.API_PARAM_SERVER_CALLBACK_URL);
        Object timeOut = getVal(params, QmpayWxNativeExcutor.API_PARAM_TIME_OUT);
        Object settleType = getVal(params, QmpayWxNativeExcutor.API_PARAM_SETTLE_TYPE);

        String signData = trxType.toString() + merchantNo.toString() + orderNum.toString() + amount.toString() + goodsName.toString() + timeOut.toString() + serverCallbackUrl.toString() + orderIp.toString() + settleType.toString() + key.toString();
        String sign = DigestUtils.md5Hex(signData);
        logger.info("签名串：{}，签名：{}",signData,sign);

        params.put(QmpayWxNativeExcutor.API_PARAM_MERCHANT_NO,merchantNo);
        params.put(QmpayWxNativeExcutor.API_PARAM_ORDER_IP,orderIp);
        params.put(QmpayWxNativeExcutor.SIGN_NAME, sign);

        String result = sendPostByKeyValue(params, QmpayWxNativeExcutor.API_URL);

        if(StringUtils.isBlank(result)){
            throw new Exception("请求qmpay的微信扫码接口失败");
        }

        Map<String, Object> responseMap = JsonUtils.toMap(result);
        Map<String, Object> resultMap = new HashMap<>();

        if(responseMap == null || !responseMap.containsKey("retCode") ||
                responseMap.get("retCode") == null || !responseMap.get("retCode").toString().equals("0000"))
        {
            logger.error("请求qmpay的微信扫码接口失败:" + result);
            return null;
        }
//        if(!isResponseValid(responseMap, key.toString(), QmpayWxNativeExcutor.SIGN_NAME,
//                QmpayWxNativeExcutor.KEY_NAME)) {
//            logger.error("请求qmpay的微信扫码返回值的签名失败:" + result);
//            return null;
//        }

        if(!responseMap.get("retCode").toString().equals("0000")) {
            logger.error("请求qmpay的微信扫码接口业务执行失败:" + result);
            resultMap.put("err_code", responseMap.get("err_code"));
            resultMap.put("err_msg", responseMap.get("err_msg"));
            return resultMap;
        }

        resultMap.put("result_code", "0");
        resultMap.put("code_url", responseMap.get("payInfo"));
        return resultMap;
    }
}
